<template>
  <div class="chat-container">
    <div class="chat-messages" ref="scrollRef">
      <div class="message" v-for="(message, index) in messages" :key="index" :class="{ 'self': message.self }">
        <div class="message-text" v-html="message.text"></div>
        <div class="message-time">{{ message.time }}</div>
      </div>
    </div>
    <div class="chat-input">
      <el-input
        placeholder="请输入"
        v-model="inputText"
        @keyup.enter="sendMessage"
      ></el-input>
      <el-button class="send-button" type="primary" @click="sendMessage">发送</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, nextTick } from 'vue';
import { ElInput, ElButton } from 'element-plus';
import { gptApi } from '@/http/api';
import MarkdownIt from 'markdown-it';

interface ChatMessage {
  text: string;
  time: string;
  self?: boolean; // 新增 self 属性
}

export default defineComponent({
  components: {
    ElInput,
    ElButton,
  },
  setup() {
    const scrollRef:any = ref(null);
    const inputText = ref('');

    const messages = ref<ChatMessage[]>([
      {
        text: '你好，我是你的智能助手，有什么可以帮你的吗？',
        time: new Date().toLocaleTimeString(),
        self: false,
      },
    ]);

    const sendMessage = async () => {
      if(inputText.value === '') return
      const message = {
        text: inputText.value,
        time: new Date().toLocaleTimeString(),
        self: true, // 发送的消息 self 属性为 true
      };
      messages.value.push(message);
      inputText.value = '';

      const md = new MarkdownIt();
      const text = await gptApi(message.text);
      // const text = '1111';

      const botMessage = {
        text: md.render(text),
        time: new Date().toLocaleTimeString(),
        self: false, // 接收的消息 self 属性为 false
      };
      messages.value.push(botMessage);

      nextTick(() => {
        scrollRef.value.scrollTop = scrollRef.value.scrollHeight;
      })
    };

    return {
      inputText,
      messages,
      sendMessage,
      scrollRef
    };
  },
});
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-messages {
  flex-grow: 1;
  overflow-y: auto;
  padding: 16px;
}

.message {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 8px;
}

.message.self { /* 给自己发送的消息添加 self 样式 */
  align-items: flex-end;
}

.message-text {
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 8px;
  font-size: 14px;
  max-width: 80%;
}

.message-time {
  margin-top: 4px;
  font-size: 12px;
  color: #999;
}

.chat-input {
  display: flex;
  align-items: center;
  padding: 16px;
}

.send-button {
  margin-left: 16px;
}
</style>
